{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ovpZyIhNIgoq"
   },
   "source": [
     "# Generating Text with an RNN\n",
     "\n",
     "## Learning objectives\n",
     "\n",
     "1. Download the Shakespeare dataset.\n",
     "2. Process the text.\n",
     "3. Create training examples and targets.\n",
     "4. Build the model.\n",
     "5. Train the model.\n",
     "6. Generate text."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "BwpJ5IffzRG6"
   },
   "source": [
    "## Introduction\n",
    "\n",
    "In this notebook, you will demonstrates how to generate text using a character-based RNN. You will work with a dataset of Shakespeare's writing from Andrej Karpathy's [The Unreasonable Effectiveness of Recurrent Neural Networks](http://karpathy.github.io/2015/05/21/rnn-effectiveness/). Given a sequence of characters from this data (\"Shakespear\"), train a model to predict the next character in the sequence (\"e\"). Longer sequences of text can be generated by calling the model repeatedly.\n",
    "\n",
    "This includes runnable code implemented using [tf.keras](https://www.tensorflow.org/guide/keras/sequential_model) and [eager execution](https://www.tensorflow.org/guide/eager). The following is the sample output when the model in this tutorial trained for 30 epochs, and started with the prompt \"Q\":"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "HcygKkEVZBaa"
   },
   "source": [
    "<pre>\n",
    "QUEENE:\n",
    "I had thought thou hadst a Roman; for the oracle,\n",
    "Thus by All bids the man against the word,\n",
    "Which are so weak of care, by old care done;\n",
    "Your children were in your holy love,\n",
    "And the precipitation through the bleeding throne.\n",
    "\n",
    "BISHOP OF ELY:\n",
    "Marry, and will, my lord, to weep in such a one were prettiest;\n",
    "Yet now I was adopted heir\n",
    "Of the world's lamentable day,\n",
    "To watch the next way with his father with his face?\n",
    "\n",
    "ESCALUS:\n",
    "The cause why then we are all resolved more sons.\n",
    "\n",
    "VOLUMNIA:\n",
    "O, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, it is no sin it should be dead,\n",
    "And love and pale as any will to that word.\n",
    "\n",
    "QUEEN ELIZABETH:\n",
    "But how long have I heard the soul for this world,\n",
    "And show his hands of life be proved to stand.\n",
    "\n",
    "PETRUCHIO:\n",
    "I say he look'd on, if I must be content\n",
    "To stay him from the fatal of our country's bliss.\n",
    "His lordship pluck'd from this sentence then for prey,\n",
    "And then let us twain, being the moon,\n",
    "were she such a case as fills m\n",
    "</pre>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_bGsCP9DZFQ5"
   },
   "source": [
    "While some of the sentences are grammatical, most do not make sense. The model has not learned the meaning of words, but consider:\n",
    "\n",
    "* The model is character-based. When training started, the model did not know how to spell an English word, or that words were even a unit of text.\n",
    "\n",
    "* The structure of the output resembles a play—blocks of text generally begin with a speaker name, in all capital letters similar to the dataset.\n",
    "\n",
    "* As demonstrated below, the model is trained on small batches of text (100 characters each), and is still able to generate a longer sequence of text with coherent structure.\n",
    "\n",
    "Each learning objective will correspond to a __#TODO__ in the notebook where you will complete the notebook cell's code before running. Refer to the [solution](../solutions/text_generation.ipynb) for reference."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "srXC6pLGLwS6"
   },
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "WGyKZj3bzf9p"
   },
   "source": [
    "### Import TensorFlow and other libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "yG_n40gFzf9s"
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "\n",
    "import numpy as np\n",
    "import os\n",
    "import time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EHDoRoc5PKWz"
   },
   "source": [
    "### Download the Shakespeare dataset\n",
    "\n",
    "Change the following line to run this code on your own data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "pD_55cOxLkAb",
    "outputId": "bb7cae41-5cb3-41d7-8808-f9cc87a1d9e0"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt\n",
      "1122304/1115394 [==============================] - 0s 0us/step\n",
      "1130496/1115394 [==============================] - 0s 0us/step\n"
     ]
    }
   ],
   "source": [
    "path_to_file = tf.keras.utils.get_file('shakespeare.txt', 'https://storage.googleapis.com/download.tensorflow.org/data/shakespeare.txt')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UHjdCjDuSvX_"
   },
   "source": [
    "### Read the data\n",
    "\n",
    "First, look in the text:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "aavnuByVymwK",
    "outputId": "49080061-5206-4869-85c9-0a954d8269bb"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Length of text: 1115394 characters\n"
     ]
    }
   ],
   "source": [
    "# TODO 1\n",
    "# Read, then decode for py2 compat.\n",
    "text = # TODO 1: Your code goes here\n",
    "# length of text is the number of characters in it\n",
    "print(f'Length of text: {len(text)} characters')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "Duhg9NrUymwO",
    "outputId": "990e7926-1e6a-443b-df4c-99529777eddf"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First Citizen:\n",
      "Before we proceed any further, hear me speak.\n",
      "\n",
      "All:\n",
      "Speak, speak.\n",
      "\n",
      "First Citizen:\n",
      "You are all resolved rather to die than to famish?\n",
      "\n",
      "All:\n",
      "Resolved. resolved.\n",
      "\n",
      "First Citizen:\n",
      "First, you know Caius Marcius is chief enemy to the people.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Take a look at the first 250 characters in text\n",
    "print(text[:250])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "IlCgQBRVymwR",
    "outputId": "d34c7915-22c3-43c8-a58c-fa1285932872"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "65 unique characters\n"
     ]
    }
   ],
   "source": [
    "# The unique characters in the file\n",
    "vocab = sorted(set(text))\n",
    "print(f'{len(vocab)} unique characters')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "rNnrKn_lL-IJ"
   },
   "source": [
    "## Process the text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LFjSVAlWzf-N"
   },
   "source": [
    "### Vectorize the text\n",
    "\n",
    "Before training, you need to convert the strings to a numerical representation. \n",
    "\n",
    "The `tf.keras.layers.StringLookup` layer can convert each character into a numeric ID. It just needs the text to be split into tokens first."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "a86OoYtO01go",
    "outputId": "1c3ff6e8-9a9a-4af5-81e6-db3008e2b519"
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2022-05-02 09:41:17.512405: I tensorflow/core/common_runtime/process_util.cc:146] Creating new thread pool with default inter op setting: 2. Tune using inter_op_parallelism_threads for best performance.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<tf.RaggedTensor [[b'a', b'b', b'c', b'd', b'e', b'f', b'g'], [b'x', b'y', b'z']]>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "example_texts = ['abcdefg', 'xyz']\n",
    "\n",
    "# Split the text into tokens\n",
    "chars = # TODO 2: Your code goes here\n",
    "chars"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "1s4f1q3iqY8f"
   },
   "source": [
    "Now create the `tf.keras.layers.StringLookup` layer:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "6GMlCe3qzaL9"
   },
   "outputs": [],
   "source": [
    "ids_from_chars = tf.keras.layers.StringLookup(\n",
    "    vocabulary=list(vocab), mask_token=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ZmX_jbgQqfOi"
   },
   "source": [
    "It converts from tokens to character IDs:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "WLv5Q_2TC2pc",
    "outputId": "3b432034-3a9b-4519-f24f-711022160ff0"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.RaggedTensor [[40, 41, 42, 43, 44, 45, 46], [63, 64, 65]]>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ids = ids_from_chars(chars)\n",
    "ids"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "tZfqhkYCymwX"
   },
   "source": [
    "Since the goal of this tutorial is to generate text, it will also be important to invert this representation and recover human-readable strings from it. For this you can use `tf.keras.layers.StringLookup(..., invert=True)`.  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uenivzwqsDhp"
   },
   "source": [
    "Note: Here instead of passing the original vocabulary generated with `sorted(set(text))` use the `get_vocabulary()` method of the `tf.keras.layers.StringLookup` layer so that the `[UNK]` tokens is set the same way."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "id": "Wd2m3mqkDjRj"
   },
   "outputs": [],
   "source": [
    "chars_from_ids = tf.keras.layers.StringLookup(\n",
    "    vocabulary=ids_from_chars.get_vocabulary(), invert=True, mask_token=None)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "pqTDDxS-s-H8"
   },
   "source": [
    "This layer recovers the characters from the vectors of IDs, and returns them as a `tf.RaggedTensor` of characters:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "c2GCh0ySD44s",
    "outputId": "1b2dbaf4-997e-404a-b871-92f05142a06e"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.RaggedTensor [[b'a', b'b', b'c', b'd', b'e', b'f', b'g'], [b'x', b'y', b'z']]>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chars = chars_from_ids(ids)\n",
    "chars"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-FeW5gqutT3o"
   },
   "source": [
    "You can `tf.strings.reduce_join` to join the characters back into strings. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "zxYI-PeltqKP",
    "outputId": "0f0d297a-0301-45c3-f76d-c3fa4a38e723"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([b'abcdefg', b'xyz'], dtype=object)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tf.strings.reduce_join(chars, axis=-1).numpy()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "id": "w5apvBDn9Ind"
   },
   "outputs": [],
   "source": [
    "def text_from_ids(ids):\n",
    "  return tf.strings.reduce_join(chars_from_ids(ids), axis=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "bbmsf23Bymwe"
   },
   "source": [
    "### The prediction task"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "wssHQ1oGymwe"
   },
   "source": [
    "Given a character, or a sequence of characters, what is the most probable next character? This is the task you're training the model to perform. The input to the model will be a sequence of characters, and you train the model to predict the output—the following character at each time step.\n",
    "\n",
    "Since RNNs maintain an internal state that depends on the previously seen elements, given all the characters computed until this moment, what is the next character?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "hgsVvVxnymwf"
   },
   "source": [
    "### Create training examples and targets\n",
    "\n",
    "Next divide the text into example sequences. Each input sequence will contain `seq_length` characters from the text.\n",
    "\n",
    "For each input sequence, the corresponding targets contain the same length of text, except shifted one character to the right.\n",
    "\n",
    "So break the text into chunks of `seq_length+1`. For example, say `seq_length` is 4 and our text is \"Hello\". The input sequence would be \"Hell\", and the target sequence \"ello\".\n",
    "\n",
    "To do this first use the `tf.data.Dataset.from_tensor_slices` function to convert the text vector into a stream of character indices."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "UopbsKi88tm5",
    "outputId": "49188edc-cab6-4058-f140-4a5872fc8439"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1115394,), dtype=int64, numpy=array([19, 48, 57, ..., 46,  9,  1])>"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_ids = ids_from_chars(tf.strings.unicode_split(text, 'UTF-8'))\n",
    "all_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "id": "qmxrYDCTy-eL"
   },
   "outputs": [],
   "source": [
    "ids_dataset = tf.data.Dataset.from_tensor_slices(all_ids)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "cjH5v45-yqqH",
    "outputId": "be9ad676-1079-4cf7-e525-130bcf313977"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "F\n",
      "i\n",
      "r\n",
      "s\n",
      "t\n",
      " \n",
      "C\n",
      "i\n",
      "t\n",
      "i\n"
     ]
    }
   ],
   "source": [
    "for ids in ids_dataset.take(10):\n",
    "    print(chars_from_ids(ids).numpy().decode('utf-8'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "id": "C-G2oaTxy6km"
   },
   "outputs": [],
   "source": [
    "seq_length = 100\n",
    "examples_per_epoch = len(text)//(seq_length+1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-ZSYAcQV8OGP"
   },
   "source": [
    "The `batch` method lets you easily convert these individual characters to sequences of the desired size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "BpdjRO2CzOfZ",
    "outputId": "dc9ba2b4-7e8f-4260-ddf2-1666679fe189"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[b'F' b'i' b'r' b's' b't' b' ' b'C' b'i' b't' b'i' b'z' b'e' b'n' b':'\n",
      " b'\\n' b'B' b'e' b'f' b'o' b'r' b'e' b' ' b'w' b'e' b' ' b'p' b'r' b'o'\n",
      " b'c' b'e' b'e' b'd' b' ' b'a' b'n' b'y' b' ' b'f' b'u' b'r' b't' b'h'\n",
      " b'e' b'r' b',' b' ' b'h' b'e' b'a' b'r' b' ' b'm' b'e' b' ' b's' b'p'\n",
      " b'e' b'a' b'k' b'.' b'\\n' b'\\n' b'A' b'l' b'l' b':' b'\\n' b'S' b'p' b'e'\n",
      " b'a' b'k' b',' b' ' b's' b'p' b'e' b'a' b'k' b'.' b'\\n' b'\\n' b'F' b'i'\n",
      " b'r' b's' b't' b' ' b'C' b'i' b't' b'i' b'z' b'e' b'n' b':' b'\\n' b'Y'\n",
      " b'o' b'u' b' '], shape=(101,), dtype=string)\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2022-05-02 09:41:50.125997: W tensorflow/core/data/root_dataset.cc:167] Optimization loop failed: Cancelled: Operation was cancelled\n"
     ]
    }
   ],
   "source": [
    "# Convert the individual characters to sequences\n",
    "sequences = # TODO 3: Your code goes here\n",
    "\n",
    "for seq in sequences.take(1):\n",
    "  print(chars_from_ids(seq))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5PHW902-4oZt"
   },
   "source": [
    "It's easier to see what this is doing if you join the tokens back into strings:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "QO32cMWu4a06",
    "outputId": "651f6df8-9c72-4cff-9aad-23edd7b9673a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'First Citizen:\\nBefore we proceed any further, hear me speak.\\n\\nAll:\\nSpeak, speak.\\n\\nFirst Citizen:\\nYou '\n",
      "b'are all resolved rather to die than to famish?\\n\\nAll:\\nResolved. resolved.\\n\\nFirst Citizen:\\nFirst, you k'\n",
      "b\"now Caius Marcius is chief enemy to the people.\\n\\nAll:\\nWe know't, we know't.\\n\\nFirst Citizen:\\nLet us ki\"\n",
      "b\"ll him, and we'll have corn at our own price.\\nIs't a verdict?\\n\\nAll:\\nNo more talking on't; let it be d\"\n",
      "b'one: away, away!\\n\\nSecond Citizen:\\nOne word, good citizens.\\n\\nFirst Citizen:\\nWe are accounted poor citi'\n"
     ]
    }
   ],
   "source": [
    "for seq in sequences.take(5):\n",
    "  print(text_from_ids(seq).numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UbLcIPBj_mWZ"
   },
   "source": [
    "For training you'll need a dataset of `(input, label)` pairs. Where `input` and \n",
    "`label` are sequences. At each time step the input is the current character and the label is the next character. \n",
    "\n",
    "Here's a function that takes a sequence as input, duplicates, and shifts it to align the input and label for each timestep:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "id": "9NGu-FkO_kYU"
   },
   "outputs": [],
   "source": [
    "def split_input_target(sequence):\n",
    "    input_text = sequence[:-1]\n",
    "    target_text = sequence[1:]\n",
    "    return input_text, target_text"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "WxbDTJTw5u_P",
    "outputId": "591f9140-9612-4b3a-f7d2-d42d9d227969"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(['T', 'e', 'n', 's', 'o', 'r', 'f', 'l', 'o'],\n",
       " ['e', 'n', 's', 'o', 'r', 'f', 'l', 'o', 'w'])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "split_input_target(list(\"Tensorflow\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {
    "id": "B9iKPXkw5xwa"
   },
   "outputs": [],
   "source": [
    "dataset = sequences.map(split_input_target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "GNbw-iR0ymwj",
    "outputId": "58635ade-f2e5-4070-ccbd-3d0b01aa6dbe"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input : b'First Citizen:\\nBefore we proceed any further, hear me speak.\\n\\nAll:\\nSpeak, speak.\\n\\nFirst Citizen:\\nYou'\n",
      "Target: b'irst Citizen:\\nBefore we proceed any further, hear me speak.\\n\\nAll:\\nSpeak, speak.\\n\\nFirst Citizen:\\nYou '\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2022-05-02 09:42:00.350906: I tensorflow/compiler/mlir/mlir_graph_optimization_pass.cc:185] None of the MLIR Optimization Passes are enabled (registered 2)\n"
     ]
    }
   ],
   "source": [
    "for input_example, target_example in dataset.take(1):\n",
    "    print(\"Input :\", text_from_ids(input_example).numpy())\n",
    "    print(\"Target:\", text_from_ids(target_example).numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "MJdfPmdqzf-R"
   },
   "source": [
    "### Create training batches\n",
    "\n",
    "You used `tf.data` to split the text into manageable sequences. But before feeding this data into the model, you need to shuffle the data and pack it into batches."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "p2pGotuNzf-S",
    "outputId": "3143eb64-a919-46e8-f80f-8a9f0b8cb284"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<PrefetchDataset shapes: ((64, 100), (64, 100)), types: (tf.int64, tf.int64)>"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Batch size\n",
    "BATCH_SIZE = 64\n",
    "\n",
    "# Buffer size to shuffle the dataset\n",
    "# (TF data is designed to work with possibly infinite sequences,\n",
    "# so it doesn't attempt to shuffle the entire sequence in memory. Instead,\n",
    "# it maintains a buffer in which it shuffles elements).\n",
    "BUFFER_SIZE = 10000\n",
    "\n",
    "dataset = (\n",
    "    dataset\n",
    "    .shuffle(BUFFER_SIZE)\n",
    "    .batch(BATCH_SIZE, drop_remainder=True)\n",
    "    .prefetch(tf.data.experimental.AUTOTUNE))\n",
    "\n",
    "dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "r6oUuElIMgVx"
   },
   "source": [
    "## Build The Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "m8gPwEjRzf-Z"
   },
   "source": [
    "This section defines the model as a `keras.Model` subclass (For details see [Making new Layers and Models via subclassing](https://www.tensorflow.org/guide/keras/custom_layers_and_models)). \n",
    "\n",
    "This model has three layers:\n",
    "\n",
    "* `tf.keras.layers.Embedding`: The input layer. A trainable lookup table that will map each character-ID to a vector with `embedding_dim` dimensions;\n",
    "* `tf.keras.layers.GRU`: A type of RNN with size `units=rnn_units` (You can also use an LSTM layer here.)\n",
    "* `tf.keras.layers.Dense`: The output layer, with `vocab_size` outputs. It outputs one logit for each character in the vocabulary. These are the log-likelihood of each character according to the model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {
    "id": "zHT8cLh7EAsg"
   },
   "outputs": [],
   "source": [
    "# Length of the vocabulary in chars\n",
    "vocab_size = len(vocab)\n",
    "\n",
    "# The embedding dimension\n",
    "embedding_dim = 256\n",
    "\n",
    "# Number of RNN units\n",
    "rnn_units = 1024"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {
    "id": "wj8HQ2w8z4iO"
   },
   "outputs": [],
   "source": [
    "class MyModel(tf.keras.Model):\n",
    "  def __init__(self, vocab_size, embedding_dim, rnn_units):\n",
    "    super().__init__(self)\n",
    "    self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n",
    "    self.gru = tf.keras.layers.GRU(rnn_units,\n",
    "                                   return_sequences=True,\n",
    "                                   return_state=True)\n",
    "    self.dense = tf.keras.layers.Dense(vocab_size)\n",
    "\n",
    "  def call(self, inputs, states=None, return_state=False, training=False):\n",
    "    x = inputs\n",
    "    x = self.embedding(x, training=training)\n",
    "    if states is None:\n",
    "      states = self.gru.get_initial_state(x)\n",
    "    x, states = self.gru(x, initial_state=states, training=training)\n",
    "    x = self.dense(x, training=training)\n",
    "\n",
    "    if return_state:\n",
    "      return x, states\n",
    "    else:\n",
    "      return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "id": "IX58Xj9z47Aw"
   },
   "outputs": [],
   "source": [
    "model = MyModel(\n",
    "    # Be sure the vocabulary size matches the `StringLookup` layers.\n",
    "    # TODO 4: Your code goes here)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "RkA5upJIJ7W7"
   },
   "source": [
    "For each character the model looks up the embedding, runs the GRU one timestep with the embedding as input, and applies the dense layer to generate logits predicting the log-likelihood of the next character:\n",
    "\n",
    "![A drawing of the data passing through the model](https://github.com/tensorflow/text/blob/master/docs/tutorials/images/text_generation_training.png?raw=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gKbfm04amhXk"
   },
   "source": [
    "Note: For training you could use a `keras.Sequential` model here. To  generate text later you'll need to manage the RNN's internal state. It's simpler to include the state input and output options upfront, than it is to rearrange the model architecture later. For more details see the [Keras RNN guide](https://www.tensorflow.org/guide/keras/rnn#rnn_state_reuse)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-ubPo0_9Prjb"
   },
   "source": [
    "## Try the model\n",
    "\n",
    "Now run the model to see that it behaves as expected.\n",
    "\n",
    "First check the shape of the output:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "C-_70kKAPrPU",
    "outputId": "89d6211b-7600-4111-df66-bf969c9cdf69"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(64, 100, 66) # (batch_size, sequence_length, vocab_size)\n"
     ]
    }
   ],
   "source": [
    "for input_example_batch, target_example_batch in dataset.take(1):\n",
    "    example_batch_predictions = model(input_example_batch)\n",
    "    print(example_batch_predictions.shape, \"# (batch_size, sequence_length, vocab_size)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Q6NzLBi4VM4o"
   },
   "source": [
    "In the above example the sequence length of the input is `100` but the model can be run on inputs of any length:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "vPGmAAXmVLGC",
    "outputId": "73a0dc59-c315-4164-c8e6-699463956187"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: \"my_model\"\n",
      "_________________________________________________________________\n",
      "Layer (type)                 Output Shape              Param #   \n",
      "=================================================================\n",
      "embedding (Embedding)        multiple                  16896     \n",
      "_________________________________________________________________\n",
      "gru (GRU)                    multiple                  3938304   \n",
      "_________________________________________________________________\n",
      "dense (Dense)                multiple                  67650     \n",
      "=================================================================\n",
      "Total params: 4,022,850\n",
      "Trainable params: 4,022,850\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "model.summary()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "uwv0gEkURfx1"
   },
   "source": [
    "To get actual predictions from the model you need to sample from the output distribution, to get actual character indices. This distribution is defined by the logits over the character vocabulary.\n",
    "\n",
    "Note: It is important to _sample_ from this distribution as taking the _argmax_ of the distribution can easily get the model stuck in a loop.\n",
    "\n",
    "Try it for the first example in the batch:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {
    "id": "4V4MfFg0RQJg"
   },
   "outputs": [],
   "source": [
    "sampled_indices = tf.random.categorical(example_batch_predictions[0], num_samples=1)\n",
    "sampled_indices = tf.squeeze(sampled_indices, axis=-1).numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "QM1Vbxs_URw5"
   },
   "source": [
    "This gives us, at each timestep, a prediction of the next character index:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "YqFMUQc_UFgM",
    "outputId": "eb5b4ad4-ce6d-4407-ff2d-530ffe1e6b5a"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 6, 43, 37, 56, 21,  4, 51, 15, 34, 20, 37, 16, 60, 65, 20, 38, 61,\n",
       "       60,  3, 45, 15, 22, 22,  1, 39, 11, 21, 56,  4, 11, 24, 49, 20, 50,\n",
       "       15, 53, 25,  9, 30, 28,  8, 53, 62, 54, 46, 31, 55, 27,  1, 52, 22,\n",
       "       54, 58, 26, 44, 64, 65, 61, 57, 65, 37, 27, 25,  0, 18, 63,  5, 26,\n",
       "       11, 46, 19, 13,  6, 12, 16,  2, 13, 56, 52, 48, 21, 13, 52, 50, 21,\n",
       "       16, 45,  8, 29, 14, 49, 19,  5, 57, 18, 23,  6, 63, 34, 20])"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sampled_indices"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LfLtsP3mUhCG"
   },
   "source": [
    "Decode these to see the text predicted by this untrained model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "xWcFwPwLSo05",
    "outputId": "e0230fe9-922e-48b3-c215-ab0ac90409ec"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Input:\n",
      " b'no sooner in,\\nBut every man betake him to his legs.\\n\\nROMEO:\\nA torch for me: let wantons light of hea'\n",
      "\n",
      "Next Char Predictions:\n",
      " b\"'dXqH$lBUGXCuzGYvu!fBII\\nZ:Hq$:KjGkBnL.QO-nwogRpN\\nmIosMeyzvrzXNL[UNK]Ex&M:gF?';C ?qmiH?mkHCf-PAjF&rEJ'xUG\"\n"
     ]
    }
   ],
   "source": [
    "print(\"Input:\\n\", text_from_ids(input_example_batch[0]).numpy())\n",
    "print()\n",
    "print(\"Next Char Predictions:\\n\", text_from_ids(sampled_indices).numpy())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "LJL0Q0YPY6Ee"
   },
   "source": [
    "## Train the model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "YCbHQHiaa4Ic"
   },
   "source": [
    "At this point the problem can be treated as a standard classification problem. Given the previous RNN state, and the input this time step, predict the class of the next character."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "trpqTWyvk0nr"
   },
   "source": [
    "### Attach an optimizer, and a loss function"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UAjbjY03eiQ4"
   },
   "source": [
    "The standard `tf.keras.losses.sparse_categorical_crossentropy` loss function works in this case because it is applied across the last dimension of the predictions.\n",
    "\n",
    "Because your model returns logits, you need to set the `from_logits` flag.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {
    "id": "ZOeWdgxNFDXq"
   },
   "outputs": [],
   "source": [
    "loss = tf.losses.SparseCategoricalCrossentropy(from_logits=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "4HrXTACTdzY-",
    "outputId": "9e7d6102-3965-4023-eaa7-0b7241095c71"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediction shape:  (64, 100, 66)  # (batch_size, sequence_length, vocab_size)\n",
      "Mean loss:         tf.Tensor(4.189847, shape=(), dtype=float32)\n"
     ]
    }
   ],
   "source": [
    "example_batch_mean_loss = loss(target_example_batch, example_batch_predictions)\n",
    "print(\"Prediction shape: \", example_batch_predictions.shape, \" # (batch_size, sequence_length, vocab_size)\")\n",
    "print(\"Mean loss:        \", example_batch_mean_loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "vkvUIneTFiow"
   },
   "source": [
    "A newly initialized model shouldn't be too sure of itself, the output logits should all have similar magnitudes. To confirm this you can check that the exponential of the mean loss is approximately equal to the vocabulary size. A much higher loss means the model is sure of its wrong answers, and is badly initialized:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "MAJfS5YoFiHf",
    "outputId": "fa556d2a-893a-40f2-dcb2-b9b5da1a12a6"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "66.01269"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tf.exp(example_batch_mean_loss).numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jeOXriLcymww"
   },
   "source": [
    "Configure the training procedure using the `tf.keras.Model.compile` method. Use `tf.keras.optimizers.Adam` with default arguments and the loss function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {
    "id": "DDl1_Een6rL0"
   },
   "outputs": [],
   "source": [
    "model.compile(optimizer='adam', loss=loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ieSJdchZggUj"
   },
   "source": [
    "### Configure checkpoints"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "C6XBUUavgF56"
   },
   "source": [
    "Use a `tf.keras.callbacks.ModelCheckpoint` to ensure that checkpoints are saved during training:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {
    "id": "W6fWTriUZP-n"
   },
   "outputs": [],
   "source": [
    "# Directory where the checkpoints will be saved\n",
    "checkpoint_dir = './training_checkpoints'\n",
    "# Name of the checkpoint files\n",
    "checkpoint_prefix = # TODO 5: Your code goes here\n",
    "\n",
    "checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n",
    "    filepath=checkpoint_prefix,\n",
    "    save_weights_only=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3Ky3F_BhgkTW"
   },
   "source": [
    "### Execute the training"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "IxdOA-rgyGvs"
   },
   "source": [
    "To keep training time reasonable, use 10 epochs to train the model. In Colab, set the runtime to GPU for faster training."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {
    "id": "7yGBE2zxMMHs"
   },
   "outputs": [],
   "source": [
    "EPOCHS = 10"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "UK-hmKjYVoll",
    "outputId": "246ba526-eca1-4b04-b3de-c4cd9090e89f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/10\n",
      "172/172 [==============================] - 398s 2s/step - loss: 2.7256\n",
      "Epoch 2/10\n",
      "172/172 [==============================] - 399s 2s/step - loss: 1.9863\n",
      "Epoch 3/10\n",
      "172/172 [==============================] - 396s 2s/step - loss: 1.7072\n",
      "Epoch 4/10\n",
      "172/172 [==============================] - 396s 2s/step - loss: 1.5468\n",
      "Epoch 5/10\n",
      "172/172 [==============================] - 394s 2s/step - loss: 1.4490\n",
      "Epoch 6/10\n",
      "172/172 [==============================] - 394s 2s/step - loss: 1.3811\n",
      "Epoch 7/10\n",
      "172/172 [==============================] - 395s 2s/step - loss: 1.3295\n",
      "Epoch 8/10\n",
      "172/172 [==============================] - 403s 2s/step - loss: 1.2850\n",
      "Epoch 9/10\n",
      "172/172 [==============================] - 401s 2s/step - loss: 1.2426\n",
      "Epoch 10/10\n",
      "172/172 [==============================] - 403s 2s/step - loss: 1.2042\n"
     ]
    }
   ],
   "source": [
    "history = model.fit(dataset, epochs=EPOCHS, callbacks=[checkpoint_callback])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "kKkD5M6eoSiN"
   },
   "source": [
    "## Generate text"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "oIdQ8c8NvMzV"
   },
   "source": [
    "The simplest way to generate text with this model is to run it in a loop, and keep track of the model's internal state as you execute it.\n",
    "\n",
    "![To generate text the model's output is fed back to the input](https://github.com/tensorflow/text/blob/master/docs/tutorials/images/text_generation_sampling.png?raw=1)\n",
    "\n",
    "Each time you call the model you pass in some text and an internal state. The model returns a prediction for the next character and its new state. Pass the prediction and state back in to continue generating text.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "DjGz1tDkzf-u"
   },
   "source": [
    "The following makes a single step prediction:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "id": "iSBU1tHmlUSs"
   },
   "outputs": [],
   "source": [
    "class OneStep(tf.keras.Model):\n",
    "  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):\n",
    "    super().__init__()\n",
    "    self.temperature = temperature\n",
    "    self.model = model\n",
    "    self.chars_from_ids = chars_from_ids\n",
    "    self.ids_from_chars = ids_from_chars\n",
    "\n",
    "    # Create a mask to prevent \"[UNK]\" from being generated.\n",
    "    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]\n",
    "    sparse_mask = tf.SparseTensor(\n",
    "        # Put a -inf at each bad index.\n",
    "        values=[-float('inf')]*len(skip_ids),\n",
    "        indices=skip_ids,\n",
    "        # Match the shape to the vocabulary\n",
    "        dense_shape=[len(ids_from_chars.get_vocabulary())])\n",
    "    self.prediction_mask = tf.sparse.to_dense(sparse_mask)\n",
    "\n",
    "  @tf.function\n",
    "  def generate_one_step(self, inputs, states=None):\n",
    "    # Convert strings to token IDs.\n",
    "    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')\n",
    "    input_ids = self.ids_from_chars(input_chars).to_tensor()\n",
    "\n",
    "    # Run the model.\n",
    "    # predicted_logits.shape is [batch, char, next_char_logits]\n",
    "    predicted_logits, states = self.model(inputs=input_ids, states=states,\n",
    "                                          return_state=True)\n",
    "    # Only use the last prediction.\n",
    "    predicted_logits = predicted_logits[:, -1, :]\n",
    "    predicted_logits = predicted_logits/self.temperature\n",
    "    # Apply the prediction mask: prevent \"[UNK]\" from being generated.\n",
    "    predicted_logits = predicted_logits + self.prediction_mask\n",
    "\n",
    "    # Sample the output logits to generate token IDs.\n",
    "    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)\n",
    "    predicted_ids = tf.squeeze(predicted_ids, axis=-1)\n",
    "\n",
    "    # Convert from token ids to characters\n",
    "    predicted_chars = self.chars_from_ids(predicted_ids)\n",
    "\n",
    "    # Return the characters and model state.\n",
    "    return predicted_chars, states"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {
    "id": "fqMOuDutnOxK"
   },
   "outputs": [],
   "source": [
    "one_step_model = OneStep(model, chars_from_ids, ids_from_chars)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "p9yDoa0G3IgQ"
   },
   "source": [
    "Run it in a loop to generate some text. Looking at the generated text, you'll see the model knows when to capitalize, make paragraphs and imitates a Shakespeare-like writing vocabulary. With the small number of training epochs, it has not yet learned to form coherent sentences."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ST7PSyk9t1mT",
    "outputId": "9e2ea147-94c9-4ca0-d4d3-3dbd91ceba68"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ROMEO:\n",
      "Comfort must not prevails\n",
      "The Christon hust ready! my the king\n",
      "So slial Anden.\n",
      "\n",
      "WARWICK:\n",
      "For him I know, his judgment, and pleases\n",
      "My son of leannorn cletger him to our coulden,\n",
      "And all my sutchead or to thy head.\n",
      "\n",
      "KATHARINA:\n",
      "I never sain your unnerself, not being.\n",
      "\n",
      "FRIAR LAURENCE:\n",
      "Would please it bare thy monu? and,\n",
      "And till my baw my husband will make him:\n",
      "Your honour lives and like a thousand dows are,\n",
      "Because fow, she, thus not revenge.\n",
      "\n",
      "TRANIO:\n",
      "What, art thou art my father;\n",
      "And let me taken up, alask, it is, my daugety.\n",
      "\n",
      "Nurse:\n",
      "Would the flower doth wish our country's die endured;\n",
      "You never have answer'd his darks;\n",
      "Stand unform to have cripposes off that\n",
      "one, Put mine about you,\n",
      "Unless the way to read a pray.\n",
      "\n",
      "KING RICHARD II:\n",
      "We were a homely assured; for the\n",
      "ire we learn of such pains,\n",
      "And give to his report of kings and knee,\n",
      "And slew my daughter or foul dinisbedning: you\n",
      "will not be here, ringer for your children\n",
      "in his giard, that my life life answers.\n",
      "Or be,--our popsidion, \n",
      "\n",
      "________________________________________________________________________________\n",
      "\n",
      "Run time: 2.5511820316314697\n"
     ]
    }
   ],
   "source": [
    "start = time.time()\n",
    "states = None\n",
    "next_char = tf.constant(['ROMEO:'])\n",
    "result = [next_char]\n",
    "\n",
    "# Generate the text\n",
    "for n in range(1000):\n",
    "# TODO 6: Your code goes here\n",
    "\n",
    "result = tf.strings.join(result)\n",
    "end = time.time()\n",
    "print(result[0].numpy().decode('utf-8'), '\\n\\n' + '_'*80)\n",
    "print('\\nRun time:', end - start)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "AM2Uma_-yVIq"
   },
   "source": [
    "The easiest thing you can do to improve the results is to train it for longer (try `EPOCHS = 30`).\n",
    "\n",
    "You can also experiment with a different start string, try adding another RNN layer to improve the model's accuracy, or adjust the temperature parameter to generate more or less random predictions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "_OfbI4aULmuj"
   },
   "source": [
    "If you want the model to generate text *faster* the easiest thing you can do is batch the text generation. In the example below the model generates 5 outputs in about the same time it took to generate 1 above. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "ZkLu7Y8UCMT7",
    "outputId": "7c575e89-ce72-454f-e154-62b7fec2ae0d"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tf.Tensor(\n",
      "[b\"ROMEO:\\nNo bear from this and hangment of her head.\\n\\nCLARENCE:\\nGo as I tread upon my lafied my.\\nSomertitile venom to the postering\\nMarch's ready into his praises of the king.\\nWill he that so to child to lost.\\n\\nKING EDWARD IV:\\nHow now, Signior Baptista,\\nHaving a noble me this body.\\nIntent to wife in jest on law us\\nWhile touch you. 3 KING RICHARD II:\\nDo ask in him: meantious nursed, Paul's, he,\\nSighs as mountain the horse of the remedy, and know I\\naccept his own and colour, not from his child,\\nWhose blood of wixters was broke thy needed:\\nMarry, smiling, what the restor\\nWill not angry and adments eyes duke:\\nThen a survant Clarence, in a lingerous pooror\\nAnd leave our souls is curbed with his feet, I\\ncleaper to you, Ortentidell in truitor,\\nO'er honour, let thee was my cates,\\nBecause I will be takening the reason cold not:\\nGod, king of Lancaster, Here, saving him,\\nShoothal I nend me forfeit of mistress,\\nSo every cause of honour mightily rud,\\nWixe to shine up but clest with Bolemia speed;\\nFor they \"\n",
      " b\"ROMEO:\\nWhat, if I am honourably forthwer?\\n\\nKING EDWARD IV:\\nThen where he pretty Blother, pray.\\nYou, sir, I can amply any oaths that his\\ncannot-brow.\\n\\nSecond Senator:\\nCome, here, here come; but not to be\\nTo fight on my pere; nor once of Juen 'am, twot'ted\\npreserved and ale, grantria and all thy intertains,\\nWhich forlow unto a little body\\nYour princely sugret\\nAnd big us soul's wife it, my deserting else,\\nAnd go and know thee: the fury do handles\\nWith night nor young: thence from heaven behall\\nThe other age may? sworn you, Buckingham,\\nTo struck me, where you have honour here.\\nGod with thy firm arm'st wars and idle,\\nAnd ten times for true.\\n\\nMONTAGUE:\\nTake the mind, and prayon so circled souls,\\nYou marry ay any sight to him: for clouds\\nMy sigh will I rever! Come, sir!\\n\\nLADY CAPULET:\\nDost this time womb'st me it? I pray go,\\nYour lords, signifred, to sun Juliet's blood-butch!\\nHills content to this: why, there at the rebales\\nOf the heavens are once put,\\nThat he such disperse thus have a foul times\\nT\"\n",
      " b\"ROMEO:\\nStill trumpeth on, and hall,\\nSo high'd valour like a good woe.\\n\\nDUKE VINCENTIO:\\n'Tis is, I can prove a wingerous\\nthry head or Such sorrow back as all\\nAs close you'er divine dead,\\nThe ordiral circumst of joys of provike? So out\\nThe commord, yet go the fastily ingrededood,\\nI'll fill homogry; here deny his viege as mine own.\\nRay, here is in the store, you abbarr'd becomes to lent;\\nthe more hang postation of Warwick,\\nWhere it was woeld, till we learn a crown;\\nAnd call't his fentering winkers grown:\\nI save the king; and with a childle for our fame\\nTo look ow. Sweet King Edward's royal falls,\\nAnd all the duy say 'tis a rather'd scene,\\nCommend to your own reconfine, forsway,\\nOf cheeks as he doth live to dancing in.\\nEven so did will I like this, friar\\nShe comes. I crave not, I'll pry our fleety.\\n\\nCLARENCE:\\n\\nWARWICK:\\nNo, marry, and be gone.\\nWhich, espect my soul! here come you well,\\nI'll anger him his partis prisoner could sing,\\nbew did I please. You slay the kit,\\nWho benother dance's death ta\"\n",
      " b\"ROMEO:\\nThe mighty-plince and dangerous and already,\\nAnd in heaven from my life is That woe.\\nLine come?\\n\\nShepherd:\\nFormeretard we here here what my part.\\n\\nKING RICHARD III:\\nEven so some pack so it is out of deligeth.\\nHow deeper the heavens are as lieast.\\n\\nJULIET:\\nTake thy odverse sun by any and one:\\nMost mortal lars,--on that of Thich lies are his:\\nThat knows you will thy king by Cause.\\n\\nMENENIUS:\\nAnd I fly such sort andotioner?\\n\\nDUKE OF YORK:\\nXadest thou thine.\\nWho? 'tis not an end of kimsering nowliss\\nconsul, valiar Coriolis, take unpanacle\\nWith the grassal own; by him touch her, how I should and\\nconsented by our adversaries,\\nwhich in my effection of the tentry curses\\nWas nothing lightly lost; your facian crown\\nand doing to his coston-easy, and thou look'd!\\nAnd he work proudder in his proud Henry, and\\ndo sibettly as I abstring wence,\\nHow muke they must blow outrous walls.\\nKill me, if I am arrived to heaven\\nDrown in the sop of scolits, shalt I fly.\\n\\nLADY ANNE:\\nWhat are they are it?\\n\\nCLAUDIO:\"\n",
      " b\"ROMEO: gentle Vonseeners, by the first house:\\nHights is prevain'd your grief;\\nOr bautefless Sigh of Since was certainly a king: these eyes\\nOr now a bloody true to woe.\\n\\nAUTOLYCUS:\\n\\nHerresse\\nSits he khate, my soul! have you looked man!\\nHe could I will kept like a way and\\nAn if I had slaid mothers' conscience\\nThou youtht being sovereign'd and advise,\\nIn veil of beauty to England,\\nWhich so beced him hither. what at thy looks!\\n\\nLADY CAPULET:\\nEven in Catesby knees, stubjers mine od,\\nBeing First And new 'bout me, lest o'erball all great,\\nWill will make a side thy enteature you guess;\\nYour comfort tender, beholders his coople\\nHis wit out one cock, say are vequent,\\nShoul heavens, kneel fair Hastings,\\nDogs by the groof, o'er bruttle-show true;\\nThese greater bencinent in Stopan Clifford's right,\\nAnonnesting I should be the cate,\\nBut transparing in his neother and my boat.\\n\\nDUKE VINCENTIO:\\nO life, sir, sir, for the grouna, uncle?\\n\\nPROSPERO:\\nBe I affrighted him to have reckon\\nThe desire they are and foo\"], shape=(5,), dtype=string) \n",
      "\n",
      "________________________________________________________________________________\n",
      "\n",
      "Run time: 4.786050081253052\n"
     ]
    }
   ],
   "source": [
    "start = time.time()\n",
    "states = None\n",
    "next_char = tf.constant(['ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:', 'ROMEO:'])\n",
    "result = [next_char]\n",
    "\n",
    "for n in range(1000):\n",
    "  next_char, states = one_step_model.generate_one_step(next_char, states=states)\n",
    "  result.append(next_char)\n",
    "\n",
    "result = tf.strings.join(result)\n",
    "end = time.time()\n",
    "print(result, '\\n\\n' + '_'*80)\n",
    "print('\\nRun time:', end - start)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "UlUQzwu6EXam"
   },
   "source": [
    "## Export the generator\n",
    "\n",
    "This single-step model can easily be [saved and restored](https://www.tensorflow.org/guide/saved_model), allowing you to use it anywhere a `tf.saved_model` is accepted."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "3Grk32H_CzsC",
    "outputId": "c32c6cd0-4424-4a9f-d5da-ac8ee92a61b5"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:Skipping full serialization of Keras layer <__main__.OneStep object at 0x7f80346d6a90>, because it is not built.\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2022-05-02 10:52:49.699055: W tensorflow/python/util/util.cc:348] Sets are not currently considered sequences, but this may change in the future, so consider avoiding using them.\n",
      "WARNING:absl:Found untraced functions such as gru_cell_layer_call_and_return_conditional_losses, gru_cell_layer_call_fn, gru_cell_layer_call_fn, gru_cell_layer_call_and_return_conditional_losses, gru_cell_layer_call_and_return_conditional_losses while saving (showing 5 of 5). These functions will not be directly callable after loading.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: one_step/assets\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: one_step/assets\n"
     ]
    }
   ],
   "source": [
    "tf.saved_model.save(one_step_model, 'one_step')\n",
    "one_step_reloaded = tf.saved_model.load('one_step')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "_Z9bb_wX6Uuu",
    "outputId": "82973de0-a27c-4b75-8769-f2a6995d290b"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ROMEO:\n",
      "The sin and talk for Causio's followers.\n",
      "Come on, do find to so; and in his nurse to sit.\n",
      "Now, for \n"
     ]
    }
   ],
   "source": [
    "states = None\n",
    "next_char = tf.constant(['ROMEO:'])\n",
    "result = [next_char]\n",
    "\n",
    "for n in range(100):\n",
    "  next_char, states = one_step_reloaded.generate_one_step(next_char, states=states)\n",
    "  result.append(next_char)\n",
    "\n",
    "print(tf.strings.join(result)[0].numpy().decode(\"utf-8\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Y4QwTjAM6A2O"
   },
   "source": [
    "## Advanced: Customized Training\n",
    "\n",
    "The above training procedure is simple, but does not give you much control.\n",
    "It uses teacher-forcing which prevents bad predictions from being fed back to the model, so the model never learns to recover from mistakes.\n",
    "\n",
    "So now that you've seen how to run the model manually next you'll implement the training loop. This gives a starting point if, for example, you want to implement _curriculum  learning_ to help stabilize the model's open-loop output.\n",
    "\n",
    "The most important part of a custom training loop is the train step function.\n",
    "\n",
    "Use `tf.GradientTape` to track the gradients. You can learn more about this approach by reading the [eager execution guide](https://www.tensorflow.org/guide/eager).\n",
    "\n",
    "The basic procedure is:\n",
    "\n",
    "1. Execute the model and calculate the loss under a `tf.GradientTape`.\n",
    "2. Calculate the updates and apply them to the model using the optimizer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {
    "id": "x0pZ101hjwW0"
   },
   "outputs": [],
   "source": [
    "class CustomTraining(MyModel):\n",
    "  @tf.function\n",
    "  def train_step(self, inputs):\n",
    "      inputs, labels = inputs\n",
    "      with tf.GradientTape() as tape:\n",
    "          predictions = self(inputs, training=True)\n",
    "          loss = self.loss(labels, predictions)\n",
    "      grads = tape.gradient(loss, model.trainable_variables)\n",
    "      self.optimizer.apply_gradients(zip(grads, model.trainable_variables))\n",
    "\n",
    "      return {'loss': loss}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4Oc-eJALcK8B"
   },
   "source": [
    "The above implementation of the `train_step` method follows [Keras' `train_step` conventions](https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit). This is optional, but it allows you to change the behavior of the train step and still use keras' `Model.compile` and `Model.fit` methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {
    "id": "XKyWiZ_Lj7w5"
   },
   "outputs": [],
   "source": [
    "model = CustomTraining(\n",
    "    vocab_size=len(ids_from_chars.get_vocabulary()),\n",
    "    embedding_dim=embedding_dim,\n",
    "    rnn_units=rnn_units)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {
    "id": "U817KUm7knlm"
   },
   "outputs": [],
   "source": [
    "model.compile(optimizer = tf.keras.optimizers.Adam(),\n",
    "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "o694aoBPnEi9",
    "outputId": "73b97f5f-9e87-4e9f-d1ea-1d570c3217a6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "172/172 [==============================] - 403s 2s/step - loss: 2.7089\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "<keras.callbacks.History at 0x7f8035a11e90>"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(dataset, epochs=1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "W8nAtKHVoInR"
   },
   "source": [
    "Or if you need more control, you can write your own complete custom training loop:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "d4tSNwymzf-q",
    "outputId": "a6bd3b2e-74ac-4757-fd7b-140909a53b23"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1 Batch 0 Loss 2.2022\n",
      "Epoch 1 Batch 50 Loss 2.0665\n",
      "Epoch 1 Batch 100 Loss 1.9271\n",
      "Epoch 1 Batch 150 Loss 1.8805\n",
      "\n",
      "Epoch 1 Loss: 1.9844\n",
      "Time taken for 1 epoch 396.41 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 2 Batch 0 Loss 1.8006\n",
      "Epoch 2 Batch 50 Loss 1.7844\n",
      "Epoch 2 Batch 100 Loss 1.6508\n",
      "Epoch 2 Batch 150 Loss 1.6179\n",
      "\n",
      "Epoch 2 Loss: 1.7016\n",
      "Time taken for 1 epoch 391.73 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 3 Batch 0 Loss 1.6268\n",
      "Epoch 3 Batch 50 Loss 1.5709\n",
      "Epoch 3 Batch 100 Loss 1.5020\n",
      "Epoch 3 Batch 150 Loss 1.5121\n",
      "\n",
      "Epoch 3 Loss: 1.5398\n",
      "Time taken for 1 epoch 389.41 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 4 Batch 0 Loss 1.4825\n",
      "Epoch 4 Batch 50 Loss 1.4293\n",
      "Epoch 4 Batch 100 Loss 1.4090\n",
      "Epoch 4 Batch 150 Loss 1.4180\n",
      "\n",
      "Epoch 4 Loss: 1.4421\n",
      "Time taken for 1 epoch 393.32 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 5 Batch 0 Loss 1.3782\n",
      "Epoch 5 Batch 50 Loss 1.3704\n",
      "Epoch 5 Batch 100 Loss 1.3516\n",
      "Epoch 5 Batch 150 Loss 1.3545\n",
      "\n",
      "Epoch 5 Loss: 1.3750\n",
      "Time taken for 1 epoch 396.70 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 6 Batch 0 Loss 1.3041\n",
      "Epoch 6 Batch 50 Loss 1.3680\n",
      "Epoch 6 Batch 100 Loss 1.3882\n",
      "Epoch 6 Batch 150 Loss 1.3705\n",
      "\n",
      "Epoch 6 Loss: 1.3231\n",
      "Time taken for 1 epoch 395.77 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 7 Batch 0 Loss 1.2585\n",
      "Epoch 7 Batch 50 Loss 1.2291\n",
      "Epoch 7 Batch 100 Loss 1.2432\n",
      "Epoch 7 Batch 150 Loss 1.2839\n",
      "\n",
      "Epoch 7 Loss: 1.2781\n",
      "Time taken for 1 epoch 392.58 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 8 Batch 0 Loss 1.2359\n",
      "Epoch 8 Batch 50 Loss 1.1756\n",
      "Epoch 8 Batch 100 Loss 1.2409\n",
      "Epoch 8 Batch 150 Loss 1.2293\n",
      "\n",
      "Epoch 8 Loss: 1.2375\n",
      "Time taken for 1 epoch 392.85 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 9 Batch 0 Loss 1.1603\n",
      "Epoch 9 Batch 50 Loss 1.1977\n",
      "Epoch 9 Batch 100 Loss 1.2003\n",
      "Epoch 9 Batch 150 Loss 1.2340\n",
      "\n",
      "Epoch 9 Loss: 1.1981\n",
      "Time taken for 1 epoch 392.23 sec\n",
      "________________________________________________________________________________\n",
      "Epoch 10 Batch 0 Loss 1.1434\n",
      "Epoch 10 Batch 50 Loss 1.1274\n",
      "Epoch 10 Batch 100 Loss 1.1277\n",
      "Epoch 10 Batch 150 Loss 1.1671\n",
      "\n",
      "Epoch 10 Loss: 1.1563\n",
      "Time taken for 1 epoch 393.01 sec\n",
      "________________________________________________________________________________\n"
     ]
    }
   ],
   "source": [
    "EPOCHS = 10\n",
    "\n",
    "mean = tf.metrics.Mean()\n",
    "\n",
    "for epoch in range(EPOCHS):\n",
    "    start = time.time()\n",
    "\n",
    "    mean.reset_states()\n",
    "    for (batch_n, (inp, target)) in enumerate(dataset):\n",
    "        logs = model.train_step([inp, target])\n",
    "        mean.update_state(logs['loss'])\n",
    "\n",
    "        if batch_n % 50 == 0:\n",
    "            template = f\"Epoch {epoch+1} Batch {batch_n} Loss {logs['loss']:.4f}\"\n",
    "            print(template)\n",
    "\n",
    "    # saving (checkpoint) the model every 5 epochs\n",
    "    if (epoch + 1) % 5 == 0:\n",
    "        model.save_weights(checkpoint_prefix.format(epoch=epoch))\n",
    "\n",
    "    print()\n",
    "    print(f'Epoch {epoch+1} Loss: {mean.result().numpy():.4f}')\n",
    "    print(f'Time taken for 1 epoch {time.time() - start:.2f} sec')\n",
    "    print(\"_\"*80)\n",
    "\n",
    "model.save_weights(checkpoint_prefix.format(epoch=epoch))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "text_generation.ipynb",
   "provenance": [],
   "toc_visible": true
  },
  "environment": {
   "kernel": "python3",
   "name": "tf2-gpu.2-6.m91",
   "type": "gcloud",
   "uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-6:m91"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
